<template>
  <div>
    <el-card class="search">
      <el-row>
        <el-col :span="6">
          <div class="divLabel">仓库名称</div>
          <el-input
            v-model="searchForm.warehouseName"
            placeholder="请输入"
          ></el-input>
        </el-col>
        <el-col :span="6">
          <div class="divLabel">库区名称</div>
          <el-input v-model="searchForm.name" placeholder="请输入"></el-input>
        </el-col>
        <el-col :span="6">
          <div class="divLabel">仓库状态</div>
          <el-select v-model="searchForm.status" placeholder="请输入" clearable>
            <el-option label="全部" value="null"></el-option>
            <el-option label="停用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <div class="divLabel"></div>
          <el-row type="flex" justify="end">
            <el-button type="primary" round @click="search">搜索</el-button>
            <el-button
              round
              style="border: none; background: #f8f5f5; margin-left: 20px"
              @click="reset"
              >重置</el-button
            >
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="table-container">
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        style="padding: 20px 30px"
      >
        <el-button type="success" round @click="add">新增仓库</el-button>
        <div class="right">
          <el-button round @click="download">下载库区模板</el-button>
          <!-- 下载模板a标签 -->
          <a
            ref="downloadTemplate"
            style="display: none"
            href="./static/areaTemplate.xlsx"
          ></a>
          <el-button round style="margin-left: 20px" @click="excelVisible = true"
            >导入库区信息</el-button>

        </div>
      </el-row>
      <el-row>
        <el-table
          :cell-style="{ borderColor: '#f5efee!important' }"
          size="small"
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{
            background: '#f9f6ee',
            borderColor: '#f5efee!important',
            fontSize: '13px',
            fontFamily: 'PingFangSC,PingFangSC-Medium',
            fontWeight: '400',
            color: '#887e7e',
          }"
        >
          <el-table-column type="index" align="center" label="序号" width="68">
          </el-table-column>
          <el-table-column
            prop="warehouseName"
            align="center"
            label="所属仓库"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="code"
            align="center"
            label="库区编号"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            align="center"
            label="库区名称"
            width="150"
          >
          </el-table-column>
          <el-table-column
            :formatter="formatTemperatureType"
            prop="temperatureType"
            align="center"
            label="温度类型"
            width="200"
          >
          </el-table-column>
          <el-table-column
            :formatter="formatBearingType"
            prop="bearingType"
            align="center"
            label="承重类型"
            width="150"
          >
          </el-table-column>
          <el-table-column
            :formatter="formatUseType"
            prop="useType"
            align="center"
            label="用途属性"
            width="150"
          >
          </el-table-column>
          <el-table-column
            :formatter="statusFormat"
            prop="status"
            align="center"
            label="库区状态"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="personName"
            align="center"
            label="负责人"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="phone"
            align="center"
            label="联系电话"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="includedNum"
            align="center"
            label="库位数量"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="updateTime"
            align="center"
            label="更新时间"
            width="150"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="180"
          >
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="edit(row)"
                >编辑</el-button
              >
              <el-button type="text" size="small" @click="toggleStatus(row)">{{
                row.status === 1 ? "停用" : "启用"
              }}</el-button>
              <el-button type="text" size="small" @click="del(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row
        type="flex"
        justify="center"
        style="margin-top: 20px; margin-bottom: 34px"
      >
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 启用/停用对话框 -->
    <el-dialog
      :title="status === 1 ? '确认停用' : '确认启用'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span
        >确认要{{ status === 1 ? "停用" : "启用" }}：{{
          warehouseName
        }}
        吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button round @click="dialogVisible = false">取 消</el-button>
        <el-button round type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 导入库区信息弹窗 -->
    <el-dialog
      title="导入库区"
      :visible.sync="excelVisible"
      width="30%"
      close="handleClose">
      <el-upload
        ref="upload"
        :auto-upload="false"
        class="upload-demo"
        drag
        action="#"
        :http-request="handleHttpRequest"
        :file-list="fileList"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button round @click="excelVisible = false">取 消</el-button>
        <el-button round type="primary" :disabled="disabled" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传后显示结果 -->
    <el-dialog
      title="导入库区"
      :visible.sync="resultVisible"
      width="30%"
      close="close">
      <div class="info">
        <div class="title">导入成功<span style="color: #00c753;">{{ result.success }}</span>条，失败<span style="color: #ff4d4f;">{{ result.fail }}</span>条</div>
        <ul>
          <li v-for="(item, index) in result.message" :key="index">{{ item }}</li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button round type="primary" @click="resultVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAreaDetail,
  delAreaData,
  updateAreaData,
  importExcel
} from '@/api/areamanage'
import constantEnum from '@/api/constant/table'
export default {
  data () {
    return {
      disabled: true,
      fileList: [],
      result: {}, // 导入excel结果
      resultVisible: false, // 结果框显示
      excelVisible: false, // 传入excel框显示
      constantEnum,
      id: '',
      warehouseName: '',
      status: '',
      dialogVisible: false,
      searchForm: {
        warehouseName: '', // 仓库名称
        name: '', // 库区名称
        status: '' // 仓库状态
      },
      tableData: [],
      page: {
        current: 1, // 当前页
        size: 10, // 每页数量
        totalPage: 0, // 总页数
        total: 0 // 总数量
      }
    }
  },
  created () {
    this.getTableList()
  },
  methods: {
    // 处理按钮禁用与启用
    handleChange () {
      this.disabled = false
    },
    // 关闭上传结果框
    close () {
      this.resultVisible = false
    },
    // 手动上传到服务器
    submitUpload (val) {
      this.$refs.upload.submit()
      this.excelVisible = false
      // 打开上传结果框
      this.resultVisible = true
      // 清空已上传的文件列表
      this.$refs.upload.clearFiles()
    },
    handleClose () {
      this.excelVisible = false
    },
    // 上传excel
    async handleHttpRequest (file) {
      const formdata = new FormData()
      formdata.append('file', file.file)
      const { data } = await importExcel(formdata)
      this.result = data
      // this.$message.success('导入库区信息成功')
    },
    // 下载库区模板
    download () {
      // 点击模板按钮触发a下载文件
      this.$refs.downloadTemplate.dispatchEvent(new MouseEvent('click'))
    },
    // async download () {
    //   // 动态引入 执行这个函数的时候才会引入
    //   const excel = await import('@/vendor/Export2Excel')
    //   // 表头数据
    //   const headers = Object.keys(constantEnum.exportExcelMapPath)
    //   // 二维数组
    //   const data = this.tableData.map(item => {
    //     return headers.map(ele => {
    //       if (ele === '温度类型') {
    //         return constantEnum.temperatureType.find(t => t.id === item[constantEnum.exportExcelMapPath[ele]])?.value
    //       } else if (ele === '承重类型') {
    //         return item[constantEnum.exportExcelMapPath[ele]] === 'ZX' ? '重型' : '轻型'
    //       } else if (ele === '用途属性') {
    //         return constantEnum.useType.find(t => t.id === item[constantEnum.exportExcelMapPath[ele]])?.value
    //       } else if (ele === '库区状态') {
    //         return item[constantEnum.exportExcelMapPath[ele]] === 1 ? '启用' : '停用'
    //       }
    //       return item[constantEnum.exportExcelMapPath[ele]]
    //     })
    //   })
    //   excel.export_json_to_excel({
    //     header: headers, // 表头 必填
    //     data: data, // 具体数据 必填 二维数组
    //     filename: 'areaTemplate' // 非必填 文件名
    //   })
    // },
    // 格式化状态
    statusFormat (row, column, cellValue, index) {
      return cellValue === 1 ? '启用' : '停用'
    },
    // 格式化温度类型
    formatTemperatureType (row, column, cellValue, index) {
      return cellValue ? constantEnum.temperatureType.find((item) => item.id === cellValue).value : ''
    },
    // 格式化承重类型
    formatBearingType (row, column, cellValue, index) {
      return cellValue === 'ZX' ? '重型' : '轻型'
    },
    // 格式化用途类型
    formatUseType (row, column, cellValue, index) {
      return cellValue ? constantEnum.useType.find((item) => item.id === cellValue).value : ''
    },
    // 新增仓库
    add () {
      this.$router.push('/warehouse/details/null')
    },
    // 编辑
    edit (row) {
      console.log(row)
      this.$router.push(`/warehouse/details/${row.id}`)
    },
    // 确定修改
    async confirm () {
      await updateAreaData({
        status: this.status === 1 ? 0 : 1,
        id: this.id
      })
      this.$message.success('状态改变成功')
      this.getTableList()
      this.dialogVisible = false
    },
    // 切换状态
    async toggleStatus (row) {
      this.warehouseName = row.name
      this.status = row.status
      this.id = row.id
      this.dialogVisible = true
    },
    // 删除
    async del (id) {
      await delAreaData({
        ids: [id]
      })
      this.$message.success('删除成功')
      this.getTableList()
    },
    // 重置
    reset () {
      this.getTableList()
      this.searchForm = {
        warehouseName: '', // 仓库名称
        name: '', // 库区名称
        id: '', // 仓库状态
        current: this.page.current,
        size: this.page.size
      }
    },
    // 搜索
    async search () {
      if (this.searchForm.status) {
        const res = await getAreaDetail({
          ...this.searchForm,
          current: this.page.current,
          size: this.page.size,
          id: ''
        })
        console.log(res)
        this.tableData = res.data.records
        this.page.size = +res.data.size
        this.page.total = +res.data.total
        this.page.totalPage = +res.data.pages
      } else {
        const res = await getAreaDetail({
          warehouseName: this.searchForm.warehouseName,
          name: this.searchForm.name,
          current: this.page.current,
          size: this.page.size,
          id: ''
        })
        console.log(res)
        this.tableData = res.data.records
        this.page.size = +res.data.size
        this.page.total = +res.data.total
        this.page.totalPage = +res.data.pages
      }
    },
    // 获取表格数据
    async getTableList () {
      const res = await getAreaDetail({
        current: this.page.current,
        size: this.page.size,
        id: '',
        name: '',
        warehouseName: ''
      })
      this.tableData = res.data.records
      this.page.size = +res.data.size
      this.page.total = +res.data.total
      this.page.totalPage = +res.data.pages
    },
    // 切换页面
    handleCurrentChange (val) {
      this.page.current = val
      this.getTableList()
      console.log(`当前页: ${val}`)
    },
    handleSizeChange (val) {
      this.page.size = val
      this.getTableList()
      console.log(`每页 ${val} 条`)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper::v-deep {
  .el-dialog__body {
    .info {
      padding: 12px 20px 20px;
      background: #f9f9f9;
      border-radius: 4px;
      border: 1px solid #eaeaea;
      color: #332929;
      line-height: 20px;
      height: 200px;
      overflow-y: auto;
      .title {
        font-size: 16px;
        padding-top: 10px;
        padding-bottom: 8px;
        text-align: center;
      }
      ul {
        padding: 0;
        margin: 0;
        li {
          display: inline-block;
          text-align: left;
          color: #b5abab;
          padding-bottom: 5px;
        }
      }
    }
  }
}
.upload-demo {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.el-select-dropdown__item.selected {
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
  font-weight: normal;
}
.search {
  height: 127px;
  padding: 10px;
  box-sizing: border-box;
  .el-row {
    .el-col {
      .divLabel {
        font-family: PingFangSC, PingFangSC-Medium;
        margin-bottom: 10px;
        height: 18px;
        font-size: 12px;
        color: #887e7e;
      }
      .el-button {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .el-input::v-deep {
        width: 270px;
        .el-input__inner {
          height: 40px;
          line-height: 40px;
          border: 1px solid #f8f5f5;
          background: #f8f5f5;
          border-radius: 6px;
          padding-left: 12px;
          padding-right: 12px;
          &::placeholder {
            color: #b5abab;
          }
        }
      }
      .el-select::v-deep {
        .el-input {
          width: 270px;
          .el-input__inner {
            height: 40px;
            line-height: 40px;
            border: 1px solid #f8f5f5;
            background: #f8f5f5;
            border-radius: 6px;
            padding-left: 12px;
            padding-right: 12px;
            &::placeholder {
              color: #b5abab;
            }
          }
        }
      }
    }
  }
}
.table-container {
  margin-top: 20px;
  padding: 0;
  ::v-deep .el-card__body {
    padding: 0;
  }
  .el-table::v-deep {
    .el-table__row--striped {
      td {
        background: #fdfcf9 !important;
      }
    }
    .el-table__row.hover-row {
      td {
        background: #fff6e2 !important;
      }
    }
  }
}
</style>
